<!--
 * @Author: zulezhe
 * @Date: 2021-01-26 14:53:42
 * @LastEditors: zulezhe
 * @LastEditTime: 2021-01-26 14:58:22
 * @Description: In User Settings Edit
 * @FilePath: \canvas\05.框架\requestAnimationFrame.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #some-element-you-want-to-animate {
        width: 100px;
        height: 100px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="some-element-you-want-to-animate"></div>
    <script>
      const element = document.getElementById("some-element-you-want-to-animate");
      let start;

      function step(timestamp) {
        if (start === undefined) start = timestamp;
        const elapsed = timestamp - start;

        //这里使用`Math.min()`确保元素刚好停在200px的位置。
        element.style.transform = "translateX(" + Math.min(0.1 * elapsed, 200) + "px)";

        if (elapsed < 20000) {
          // 在两秒后停止动画
          window.requestAnimationFrame(step);
        }
      }

      window.requestAnimationFrame(step);
    </script>
  </body>
</html>
